/*
 * Copyright  bocmbci
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { CordovaBridge } from './CordovaBridge';
import { PluginResult, PluginResultStatus } from './PluginResult';

export class CallbackContext{
  private callbackId: string;
  protected finished: boolean;

  private cordovaBridge: CordovaBridge;

  constructor(_callbackId: string, cordovaBridge: CordovaBridge) {
    this.callbackId = _callbackId;
    this.cordovaBridge = cordovaBridge;
  }

  sendPluginResult(pluginResult: PluginResult){
    if (this.finished) {
      console.debug("Attempted to send a second callback for ID: " + this.callbackId + "\nResult was: " + pluginResult.getMessage());
      return;
    } else {
      this.finished = !pluginResult.getKeepCallback();
    }

    this.cordovaBridge.getJsMessageQueue().addPluginResult(pluginResult, this.callbackId);
  }

  success(message: string){
    this.sendPluginResult(new PluginResult(PluginResultStatus.OK, message));
  }

  error(message: string){
    this.sendPluginResult(new PluginResult(PluginResultStatus.ERROR, message));
  }
}